Express is a node.js 您所在的位置:网站首页 JavaScript Static Methods Express is a node.js

Express is a node.js

2023-01-13 15:05| 来源: 网络整理| 查看: 265

Article directory Expressinstallation methodInstructions routingconfigure router★CaseAPI for request and response middlewarestatic filesejs templateGETPOST

Express

Express: a framework for quickly building servers under the node platform

installation method //Select the directory to be installed D:\Java\learning\nodejs\src\com\xiaozhan\express> Type: npm init --yes //Then download it in this directory Command: cnpm install express --save //Note: When it is reported that npm does not support the same name, change the name to another name in package.json Instructions const express = require('express');//Introduce express to create URL server const app = express();//Create app service object app.get('/', function (req, res) { //request, response res.send('Hello World'); }); app. listen(3000, function (err) { if (!err) console.log("The server started successfully") else console. log(err) }); //Save and run after the input is successful, enter http://localhost:3000 in the browser and the specified Hello World will pop up routing

What is routing? Routing is to decide who will respond to the client's request (defined URL)

configure router In node.js, the so-called "routing" is the back-end routing;Routing is a combination of key-value, key: request method + URI path, value: callback functionWhen requested, match in sequence, if the match is successful, do not continueRequirements: The request method must be: GET, and the requested URI must be "/meishi" // first level routing app.get('/meishi', function (request, response) { response.send("Food"); }); //Secondary route app.get('/meishi/mian', function (request, response) { response.send("Gourmet-Jajiangmen page"); }); //root route app. post('/', function (request, response) { response.send('You sent a post request'); }); // route placeholder parameters app.post('/meishi/:id', function (request, response) { response.send('id:123'); }); /* :id is a placeholder At this time, the route can also be called http://localhost/meishi/123 :id corresponds to 123 No need to write in the form of http://localhost/home?name=123 You can write /:name/:age after :id id, name, age are the attributes of the object */

complete simple code

const express = require('express'); const app = express(); app.get('/', function (req, res) { res.send('Hello World'); }); //only this step is added app.get('/post', function (request, response) { response.send('You sent a post request'); }); app. listen(3000, function (err) { if (!err) console.log('The server started successfully') else console. log(err) }) console.log('Server running at http://127.0.0.1:3000/'); //Console output prompt

parameter routing

Parameter routing can dynamically receive parameters

let express = require("express"); let app = express(); app.get('/meishi/:id', function (request, response) { console.log(request.params);//parameter routing parameters let { id} = request.params;//id is not hard-coded response.send(`I am the merchant changed to ${ id}`)//${id} dynamic id }) app. listen(3000, function (err) { if(!err) console. log("ok"); else console. log(err); }); ★Case

Node uses express routing router

// app.js homepage const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const mysql = require('mysql'); const router = require('./index') // Import routing // open the database const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test', multipleStatements: true, //Allow multiple statements to be executed }) connection. connect(() =>{ console.log('Link succeeded') }); app.use(bodyParser.urlencoded({ extends: true })); //Set up cross-domain access app.all('*', (req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By", ' 3.2.1'); res.header("Content-Type", "application/json;"); next(); }); // Use route /index is the route pointing to the name app. use(`/index`, router) //Configure service port var server = app. listen(3000, () => { const hostname = 'localhost'; const port = 3000; console.log(`Server running at http://${ hostname}:${ port}/`); }) //Create a new index.js file const express = require(`express`) const router = express. Router() router. use((req, res, next) => { console.log(`Routing executed successfully~~~`, Date.now()); next() }) router.get(`/`, (req, res, next) => { res.json({ status: 200, data: `request succeeded` }) }) router.get(`/data`, (req, res, next) => { res.json({ status: 200, data: [1, 2, 3, 4, 5, 6, 7] }) }) module.exports = router //expose the module API for request and response

1. request object: (generally take parameters)

1. request.query : Get query string parameters (query parameters), get an object 2. request.params : Get the parameters of the get request parameter route, and get an object 3. request.body : Get the post request body parameters, and get an object (cannot be used directly, you need to use a middleware) 4. request.get(xxxx): Get the value corresponding to the specified key in the request header.

2. Response object:

1. response.send() : Make a response to the browser 2. response.end() : Make a response to the browser (the response header will not be automatically appended); only end once 3. response.download() : Tell the browser to download a file, you can pass a relative path 4. response.sendFile( __dirname+'/path'): Send a file to the browser. Note: Absolute path must be passed 5. response.redirect() : Redirect to a new address (url) 6. response.set(key,value) : Custom response header content 7. response.get(key): Get the value corresponding to the specified key in the response header, rarely used 8. response.status(code): Set the response status code middleware

Concept: It is essentially a function, including three parameters: request, response, next

effect:

execute any codeModify request object, response objectEnd request-response loop (let a request get a response)Call the next middleware or route in the stack

Classification:

Application (global) level middleware (filtering illegal requests, such as anti-leech) – first way of writing: app.use((request,response,next)=>{}) – second way of writing: use function definitionThird-party middleware, namely: not built in Node, nor built in express (middleware downloaded through npm, such as body-parser) –app.use(bodyParser.urlencoded({extended:true})) –Installation instructions: npm install body-parserBuilt-in middleware (encapsulated middleware inside express) –app.use(express.urlencoded({extended:true})) –app.use(express.static('public')) //Expose static resourcesRouter middleware (Router) – later

Notice:

In express, when defining routes and middleware, according to the order of the code, put each defined middleware or route in a container similar to an array (arrays are executed in order), and match them in turn when requested , handed over to routing or middleware for processingFor the server, there is only one request object and response object for a request, and any other request and response are the introduction of both const express = require('express'); const app = express(); //middleware //================ The first middleware writing method ================ //The first door of all requests ------- use this method when all requests have to go through some processing app.use((request,response,next)=>{ //Image anti-leech if(request. get('Referer')){ let miniReferer = request.get('Referer').split('/')[2] if(miniReferer === 'localhost:63347'){ next();//pass the next }else{ // hotlink occurred response.sendFile(__dirname+'/public/err.png')//anti-leech picture } }else{ next() } }) //============ The second way of writing middleware ============ // More flexible, not the first door, can be used wherever needed. function guardPic(request,response,next) { //guardPic //anti-leech if(request. get('Referer')){ let miniReferer = request.get('Referer').split('/')[2] if(miniReferer === 'localhost:63347'){ next(); }else{ // hotlink occurred response.sendFile(__dirname+'/public/err.png') } }else{ next() } } //================== Built-in middleware ==================== //Parse the urlencoded parameters carried in the request body of the post request into an object, and then mount it on the request object app.use(express.urlencoded({ extended: true})) //================== Built-in middleware ==================== //Use built-in middleware to expose static resources - hand over all the resources in the folder you specified at one time. app.use(express.static(__dirname+'/public')) //=========================================== app.get('/',(request,response)=>{ console.log(request.demo) response. send('ok') }) app.get('/demo',(request,response)=>{ console.log(request.demo) console.log(request.query) response. send('ok2') }) app.get('/picture', guardPic, (request, response) => { response.sendFile(__dirname+'/public/demo.jpg') }) app.post('/test',(request,response)=>{ console.log(request.body) response. send('ok') }) app. listen(3000, function (err) { if(!err) console. log('ok') else console. log(err) }); //Install via npm command: npm install body-parser //third-party middleware const express = require('express') //Introduce body-parser for parsing post parameters const bodyParser = require('body-parser') const app = express() //Use third-party middleware bodyParser //Parse the urlencoded parameters carried in the request body of the post request into an object, and then mount it on the request object app.use(bodyParser.urlencoded({ extended: true}))//incoming object {} app.post('/test',(request,response)=>{ //post console.log(request.body) response. send('ok') }) Sex name: Age: static files

Express provides a built-in middleware express.static to set static files such as images, CSS, JavaScript, etc.

You can use express.static middleware to set static file path. For example: to put images, CSS, and JavaScript files in the public directory, you can write:

app.use('/public', express.static('public'));

You can store a picture in public; for example: public/images/logo.jpg store logo.jpg in images

Implementation code:

var express = require('express'); var app = express(); app.use('/public', express.static('public')); app.get('/', function (req, res) { res. send('World'); }).listen(5000); //Access in the browser: http://localhost:5000/ to display the world //Access in a browser: http://localhost:5000/public/images/logo.jpg will display a picture ejs template

​ EJS is a simple template language that helps you generate HTML pages using ordinary JavaScript code.

npm install ejs

Installation: npm install ejs

Reproduced (simple use case of EJS)

GET Account: Password: var express = require('express'); var app = express(); var bodyParser = require('body-parser');//Create application/x-www-form-urlencoded encoding analysis var urlencodedParser = bodyParser. urlencoded({ G extended: false }) app.use('/public', express.static('public')); app.get('/index.html', function (req, res) { //res. sendFile(path[, options][, fn]) //Transfer the file with the specified path - the Content-Type will be automatically set according to the file extension res.sendFile( __dirname + "/" + "index.html" ); }); app.post('/process_post', urlencodedParser, function (req, res) { // Output in JSON format var response = { "first_name": req.body.first_name, "last_name": req.body.last_name }; console. log(response); res.end(JSON.stringify(response)); }).listen(5000);

Browser access: http://localhost:5000/index.htm displays a login page and clicks on login to jump to the /process_post page

POST

File Upload

File upload: Select a file to upload: var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer');//Multer is a node.js middleware app.use('/public', express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'}).array('image')); app.get('/index.html', function (req, res) { res.sendFile( __dirname + "/" + "index.html" ); }) app.post('/file_upload', function (req, res) { console.log(req.files[0]); // uploaded file information var des_file = __dirname + "/" + req.files[0].originalname; fs.readFile( req.files[0].path, function (err, data) { fs.writeFile(des_file, data, function (err) { if( err ){ console. log( err ); }else{ response = { message:'File uploaded successfully', filename:req.files[0].originalname }; } console. log( response ); res. end( JSON. stringify( response ) ); }); }); }) var server = app. listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Application instance, access address is http://%s:%s", host, port) })


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有